<template>
  <view class="form-page">
    <u-navbar is-back :title="title" :hair-line="false"></u-navbar>
    <form class="form">
      <div class="form-body">
        <template v-for="(t,index) in mobileEntityModeList">
          <view v-if="index === 0">
            <form-item v-for="f in t.mobileFieldModeList"
                       ref="formItem"
                       :key="f.fieldId"
                       :tableData="t.data[0]"
                       :value="t.data[0][f.fieldname]"
                       :taskStatus='taskData.wfTaskModel.status'
                       :fieldModel='f'
                       @input="changeValue($event,t.data[0],f.fieldname)"
                       @changeTableData="changeTableData($event,t.data[0])"
                       :tableAc='t.ac'></form-item>
          </view>

          <view v-else-if="t.entityname !== 'J_WLHTJSFYMI'" :key="t.entityname">
            <template v-if="showSubTable">
              <view class="sub-table" v-for="(subData,subIndex) in t.data" :key="subData.ID">
                <view class="table-name">
                  {{ t.entitytitle }} ({{ subIndex + 1 }})
                  <view
                      v-if="(t.ac.split(',').indexOf('4')==-1 && openStatus==8 && ([0,1,2,5].indexOf(taskData.wfTaskModel.status)!=-1)) "
                      class="deleteDataBtn" @click="deleteSubData(t,subData,subIndex)">
                    删除
                  </view>
                </view>

                <form-item v-for="f in t.mobileFieldModeList"
                           :key="f.fieldId"
                           ref="formItem"
                           :tableData="subData"
                           :value="subData[f.fieldname]"
                           :taskStatus='taskData.wfTaskModel.status'
                           :fieldModel='f'
                           @changeTableData="changeTableData($event,subData)"
                           @input="changeValue($event,subData,f.fieldname)"
                           :tableAc='t.ac'
                ></form-item>
              </view>
              <u-button
                  v-if="t.ac.split(',').indexOf('1')==-1 && openStatus==8 && ([0,1,2,5].indexOf(taskData.wfTaskModel.status))!=-1"
                  :hair-line="false" ripple class="add-sub-table" @click="addSubData(t)"
                  :custom-style="{border: 'none'}">
                增加{{ t.entitytitle }}
              </u-button>
            </template>
            <view v-else class="float-btn" style="text-align:center;">
              <u-button
                  size="mini"
                  :hair-line="false" ripple class="add-sub-table"
                  :custom-style="{border:'none',
                    outline:'none',
                    fontSize:'30rpx',
                    padding:'30rpx',
                    margin:'20rpx auto 0',
                    backgroundColor:'#5489bb',
                    color:'#FFF'}"
                  @click="toDetail">
                {{ t.entitytitle }}
              </u-button>
            </view>
          </view>
        </template>

        <audit-records style="margin-top: 20rpx;" v-if="taskData&&showSubTable&&taskData.auditLogList.length"
                       :auditLogList="taskData.auditLogList"></audit-records>
      </div>
      <view class="float-button" v-if="openStatus==8">
        <view class="button-group">
          <template v-if="taskData">
            <template v-if="taskData.wfTaskModel.status == 4">
              <u-button :custom-style="customButton" class="reject" ripple @click="addSignAfter('不同意')">不同意</u-button>
              <u-button :custom-style="customButton" class="agree" ripple @click="addSignAfter('同意')">同意</u-button>
            </template>

            <template v-else-if="taskData.wfTaskModel.status == 3">
              <u-button :custom-style="customButton" class="reject" ripple @click="circulate">传阅</u-button>
              <u-button :custom-style="customButton" class="agree" ripple @click="circulateAfter">传阅完毕</u-button>
            </template>
            <template v-else-if=" taskData.wfTaskModel.status == 5">
              <u-button ripple @click="modifiedTask">修改完毕</u-button>
            </template>
            <template v-else-if=" taskData.wfTaskModel.status == 7">
              <u-button ripple @click="circulateAfter">接收通知</u-button>
            </template>

            <template v-else>
              <template v-if='taskData.wfStepAuditModeList.length>2'>
                <u-button :custom-style="customButton" class='reject' @click='showMore' ripple>
                  更多
                </u-button>

                <u-button :custom-style="customButton" class="isAddSign" ripple
                          v-if="taskData.wfStepModel.isAddSign == 1"
                          @click="toBuddyList">
                  加签
                </u-button>

                <u-button :custom-style="customButton" class="isCirculate" ripple
                          v-if="taskData.wfStepModel.isCirculate == 1"
                          @click="circulate">
                  传阅
                </u-button>

                <u-button :custom-style="customButton" @click="sendAudit(0)" ripple class="agree"
                          v-if="taskData.wfStepAuditModeList.length>0">
                  {{ taskData.wfStepAuditModeList[0].auditName }}
                </u-button>

              </template>

              <template v-else-if="taskData.wfStepAuditModeList.length === 2">
                <u-button :custom-style="customButton" class='reject' @click='sendAudit(1)' ripple>
                  {{ taskData.wfStepAuditModeList[1].auditName }}
                </u-button>

                <u-button :custom-style="customButton" class="isAddSign" ripple
                          v-if="taskData.wfStepModel.isAddSign == 1"
                          @click="toBuddyList">
                  加签
                </u-button>
                <u-button :custom-style="customButton" class="isCirculate" ripple
                          v-if="taskData.wfStepModel.isCirculate == 1"
                          @click="circulate">
                  传阅
                </u-button>

                <u-button :custom-style="customButton" @click="sendAudit(0)" ripple class="agree"
                          v-if="taskData.wfStepAuditModeList.length>0">
                  {{ taskData.wfStepAuditModeList[0].auditName }}
                </u-button>

              </template>


              <template v-else>
                <u-button :custom-style="customButton" class="isAddSign" ripple
                          v-if="taskData.wfStepModel.isAddSign == 1"
                          @click="toBuddyList">
                  加签
                </u-button>
                <u-button :custom-style="customButton" class="isCirculate" ripple
                          v-if="taskData.wfStepModel.isCirculate == 1"
                          @click="circulate">
                  传阅
                </u-button>
                <u-button :custom-style="customButton" @click="sendAudit(0)" ripple class="agree"
                          v-if="taskData.wfStepAuditModeList.length>0">
                  {{ taskData.wfStepAuditModeList[0].auditName }}
                </u-button>
                <u-button :custom-style="customButton" @click="sendAudit(-1)" ripple class="agree"
                          v-if="taskData.wfStepAuditModeList.length==0">
                  办理
                </u-button>
              </template>
            </template>
          </template>
        </view>
      </view>
    </form>
  </view>
</template>

<script>


import FormItem from "../../components/form-item/form-item";
import {
  routeTo,
  lengthText,
  IsDate,
  IsNumber
} from "../../utils/util";
import UButton from "../../uview-ui/components/u-button/u-button";
import AuditRecords from '../../components/audit-records.vue'

const customButton = {
  color: '#FFFFFF',
  backgroundColor: '#5f8ab4',
  width: '100%',
  border: 'none',
  borderRadius: '0'
}

export default {
  provide() {
    let that = this
    return {
      formId() {
        return that.mobileEntityModeList[0].data[0].ID
      },
      sessionId() {
        return that.userInfo.sessionId
      },
      userNo() {
        return that.userInfo.userModel.userNo
      },
      flowId() {
        return that.taskData.wfTaskModel.flowId
      },
      taskData: () => that.taskData
    }
  },
  components: {
    UButton,
    FormItem,
    AuditRecords
  },
  data() {
    return {
      showRef:false,
      customButton: customButton,
      taskData: null,
      more: true,
      id: '',
      originData: '',
      openStatus: '',
      auditIndex: 0,
      scan: false,
      title: ''
    }
  },
  computed: {
    showSubTable() {
      let flag = true
      if (this.openStatus == 9) return true
      if (!this.taskData) return flag
      switch (this.taskData.wfTaskModel.flowId) {
        case "2c9110d177c344660177fbc15b6b5233":
        case '2c9110d177c344660177ccea886b1354':
        case '2c9110d177c344660177cd8e1b071b07':
          flag = false
          break
      }
      return flag
    },
    userInfo() {
      return this.$store.state.userInfo
    },
    rejectButton() {
      return {
        ...customButton,
        color: '#0086FE',
        backgroundColor: '#FFFFFF',
        borderColor: '#0086FE'
      }
    },
    isAddSignButton() {
      return {
        ...customButton,
        color: '#0086FE',
        backgroundColor: ' #FFF',
        borderColor: ' #0086FE',
        borderRight: '0px',
      }
    },
    isCirculate() {
      return {
        ...customButton,
        color: '#0086FE',
        backgroundColor: '#FFF',
        borderColor: '#0086FE',
      }
    },
    mobileEntityModeList() {
      if (this.taskData) {
        return this.taskData.mobileEntityModeList
      } else {
        return []
      }
    }
  },
  methods: {
    async toDetail() {
      let link, params = {};
      switch (this.taskData.wfTaskModel.flowId) {
        case "2c9110d177c344660177ccea886b1354":
          link = 'box-feedback'
          break
        case "2c9110d177c344660177cd8e1b071b07":
          link = 'empty-report'
          break
        case "2c9110d177c344660177fbc15b6b5233":
          params.xcrzh = this.mobileEntityModeList[0].data[0].XCRZH
          link = 'business-confirm'
          break
      }
      params.id = this.taskData.wfTaskModel.instanceId;
      await this.saveData()
      this.showRef = true
      this.routeTo({
        link: link,
        params: params
      })
    },
    changeTableData(e, obj) {
      obj[e.key] = e.value
    },
    changeValue(value, obj, filedName) {
      obj[filedName] = value
    },
    async saveSubTableData() {
      if (this.mobileEntityModeList.length > 1) {
        uni.showLoading({
          title: '正在保存子表数据',
          mask: true
        })
        let results = []
        for (let i = 1; i < this.mobileEntityModeList.length; i++) {
          for (let j = 0; j < this.mobileEntityModeList[i].data.length; j++) {
            if (this.mobileEntityModeList[i].data[j].isModify) {
              let res = await this.api.saveFormData({
                taskId: this.taskData.wfTaskModel.id,
                instanceId: this.mobileEntityModeList[i].data[j].INSTANCEID,
                formDate: this.mobileEntityModeList[i].data[j],
                entityTableName: this.mobileEntityModeList[i].entityname,
                formId: this.taskData.wfStepModel.formId,
                mainId: this.mobileEntityModeList[i].data[j].ID
              })
              this.mobileEntityModeList[i].data[j].isModify = false
              results.push(res)
            } else {
              console.log('未修改不保存');
            }
          }
        }
        console.log(results);
        uni.showToast({
          title: '保存成功'
        })
      }
    },
    deleteSubData(tableData, subData, index) {
      let that = this;
      uni.showModal({
        content: `你确定要删除${ tableData.entitytitle } ${ index + 1 } 吗`,
        async success(res) {
          if (res.confirm) {
            uni.showLoading({
              mask: true,
              title: '正在删除'
            })
            let data = await that.api.deleteSubData({
              ids: subData.ID,
              tableName: tableData.entityname,
              flowId: that.taskData.wfTaskModel.flowId,
              stepId: that.taskData.wfTaskModel.stepId,
              instanceId: that.taskData.wfTaskModel.instanceId
            })
            if (data.code === 0) {
              uni.showToast({
                title: '删除成功'
              })
              // tableData.data.remove(subData);
              tableData.data.splice(index, 1)
              /*that.mobileEntityModeList.forEach((t,idx) => {
                if (t.entityname == tableData.entityname) {
                  t.data.splice(idx, 1);
                }
              })*/
            } else {
              uni.showModal({
                title: '提示',
                content: data.msg,
                showCancel: false
              })
            }
          }
        }
      })

    },
    async addSubData(tableEntity) {
      uni.showLoading({
        mask: true,
        title: '加载中'
      })
      let data = await this.api.addSubData({
        instanceId: this.taskData.wfTaskModel.instanceId,
        tablename: tableEntity.entityname
      })
      tableEntity.data.push(data.data)
      uni.hideLoading()
    },
    addSignAfter(signvalue) {
      let taskId = this.taskData.wfTaskModel.id;
      let stepId = this.taskData.wfTaskModel.stepId;
      let flowId = this.taskData.wfModel.id;
      routeTo({
        link: 'addsign',
        params: {
          flowId: flowId,
          stepId: stepId,
          taskId: taskId,
          signvalue: signvalue
        }
      })
    },
    circulate() {
      let that = this;
      routeTo({
        link: "buddyList",
        events: {
          async sendContactData(res) {
            console.log(res, "传阅获取的人")
            if (res.data.length > 0) {
              let targets = [];
              res.data.forEach((user, i) => {
                targets.push(user.userId)
              })
              if (targets.length > 0) {
                //执行传阅任务
                uni.showLoading({
                  title: '传阅中',
                  mask: true,
                })
                uni.showNavigationBarLoading();
                let title = that.taskData.wfTaskModel.title;
                title = title.indexOf("[传阅]") == -1 ? "[传阅]" + title : title;
                let res = await that.api.circulate_send({
                  taskId: that.taskData.wfTaskModel.id,
                  flowId: that.taskData.wfTaskModel.flowId,
                  stepId: that.taskData.wfTaskModel.stepId,
                  title: title,
                  target: targets.join(" "),
                  priority: 0
                })
                if (res.code == 0) {
                  if (res.data == "") {
                    uni.showToast({
                      title: '传阅成功!',
                      duration: 2000,
                    });
                  } else {
                    uni.showToast({
                      title: res.data,
                      duration: 2000,
                      icon: "none"
                    });
                  }
                } else {
                  uni.showToast({
                    title: res.msg,
                    duration: 2000,
                    icon: "none"
                  });
                }
              }

            }
          }
        },
        params: {
          actionType: 'circulate'
        }
      })
    },
    toBuddyList() {
      let that = this;
      routeTo({
        link: "buddyList",
        events: {
          async sendContactData(res) {
            if (res.data.length > 0) {
              let targets = [];
              res.data.forEach((user, i) => {
                targets.push(user.userId)
              })
              if (targets.length > 0) {
                //执行加签任务
                uni.showLoading({
                  title: '加签中',
                  mask: true,
                })
                uni.showNavigationBarLoading();
                let res = await that.api.addSignSend({
                  sessionId: that.userInfo.sessionId,
                  taskId: that.taskData.wfTaskModel.id,
                  flowId: that.taskData.wfTaskModel.flowId,
                  stepId: that.taskData.wfTaskModel.stepId,
                  title: that.taskData.wfTaskModel.title,
                  target: targets.join(" ")
                })
                uni.hideLoading();
                uni.hideNavigationBarLoading()
                if (res.code == 0) {
                  if (res.data == "") {
                    uni.showToast({
                      title: '任务办理成功!',
                      duration: 2000,
                    });

                    setTimeout(function () {
                      uni.navigateBack({
                        delta: 1,
                      })
                      uni.$emit('update', {
                        payload: '刷新待办'
                      })
                    }, 2000)
                  } else {
                    uni.showToast({
                      title: res.data,
                      duration: 2000,
                      icon: "none"
                    });
                  }
                } else {
                  uni.showToast({
                    title: res.msg,
                    duration: 2000,
                    icon: "none"
                  });
                }
              }

            }
          }
        },
        params: {
          actionType: 'addSign'
        }
      })
    },
    /**校验表格数据
     * @param {Object} verifyNull true 校验必填 false 不校验必填(单独保存时候写false)
     */
    verifyData(verifyNull) {
      let status = true;
      this.mobileEntityModeList.some(function (item, index) {
        //校验数据
        let data = item.data;
        item.mobileFieldModeList.some(function (field_item, field_index) {
          if (!status) {
            return true;
          }
          let fieldname = field_item.fieldname;
          let fieldtitle = field_item.fieldtitle;
          let fieldtype = field_item.fieldtype;
          let ui = field_item.ui;
          let fieldength = field_item.fieldength;
          let isNull = field_item.null; //如果是true 字段不能为空
          data.some((data_item, data_index) => {
            let data_value = data_item[fieldname];
            if (fieldtype == "文本" || fieldtype == "大文本") {
              if (ui == "图片附件") {
                //后期校验
              } else if (ui == "附件") {
                //后期校验
              } else if (ui == "日期" || ui == "日期时间") {
                if (isNull && verifyNull) {
                  if (lengthText(data_value) == 0) {
                    uni.showToast({
                      title: fieldtitle + '必须填写!',
                      duration: 2000,
                      icon: "none"
                    });
                    status = false;
                    return true;
                  }
                  if (!IsDate(data_value)) {
                    uni.showToast({
                      title: fieldtitle + '日期格式不正确!',
                      duration: 2000,
                      icon: "none"
                    });
                    status = false;
                    return true;
                  }
                }
                if (!IsDate(data_value)) {
                  uni.showToast({
                    title: fieldtitle + '日期格式不正确!',
                    duration: 2000,
                    icon: "none"
                  });
                  status = false;
                  return true;
                }
              } else {
                if (isNull && verifyNull) {
                  if (lengthText(data_value) == 0) {
                    uni.showToast({
                      title: fieldtitle + '必须填写!',
                      duration: 2000,
                      icon: "none"
                    });
                    status = false;
                    return true;
                  }
                }
                //长度校验
                if (lengthText(data_value) > parseInt(fieldength)) {
                  uni.showToast({
                    title: fieldtitle + '最大输入' + fieldength + '个字符!',
                    duration: 2000,
                    icon: "none"
                  });
                  status = false;
                  return true;
                }
              }
            } else if (fieldtype == "日期") {
              if (isNull && verifyNull) {
                if (lengthText(data_value) == 0) {
                  uni.showToast({
                    title: fieldtitle + '必须填写!',
                    duration: 2000,
                    icon: "none"
                  });
                  status = false;
                  return true;
                }
              }
              if (!IsDate(data_value)) {
                uni.showToast({
                  title: fieldtitle + '日期格式不正确!',
                  duration: 2000,
                  icon: "none"
                });
                status = false;
                return true;
              }
            } else if (fieldtype == "数值") {
              if (isNull && verifyNull) {
                if (lengthText(data_value) == 0) {
                  uni.showToast({
                    title: fieldtitle + '必须填写!',
                    duration: 2000,
                    icon: "none"
                  });
                  status = false;
                  return true;
                }
              }
              if (!IsNumber(data_value)) {
                uni.showToast({
                  title: fieldtitle + '只能输入数值!',
                  duration: 2000,
                  icon: "none"
                });
                status = false;
                return true;
              } else {
                if (data_value.indexOf('.') == -1) {
                  if (data_value.length > parseInt(fieldength) && fieldength.indexOf(",") == -1) {
                    uni.showToast({
                      title: fieldtitle + "值过长了，该字段最多可输入" + fieldength + "位数字!",
                      duration: 2000,
                      icon: "none"
                    });
                    status = false;
                    return true;
                  }
                } else {
                  var fLength = parseInt(fieldength.substring(0, fieldength.indexOf(",")));
                  var bLength = parseInt(fieldength.substring(fieldength.indexOf(",") + 1, fieldength.length));
                  var length = fLength - bLength;
                  if (lengthText(data_value.split(".")[0]) > length) {
                    let msg = "整数位数过长，该字段最多可输入" + length + "个整数字符" + bLength + "个小数！";
                    uni.showToast({
                      title: fieldtitle + msg,
                      duration: 2000,
                      icon: "none"
                    });
                    status = false;
                    return true;
                  }
                  if (data_value.indexOf('.') != -1) {
                    if (lengthText(data_value.split(".")[1]) > bLength) {
                      let msg = "小数点位数过长，该字段最多可输入" + length + "个整数字符" + bLength + "个小数！";
                      uni.showToast({
                        title: fieldtitle + msg,
                        duration: 2000,
                        icon: "none"
                      });
                      status = false;
                      return true;
                    }
                  }

                }
              }
            }
          })

        })
      });
      return status;

    },
    async saveAudit() {
      uni.showLoading({
        title: '保存数据',
        mask: true,
      })
      uni.showNavigationBarLoading();
      let data = await this.api.saveAudit({
        auditOption: (this.auditIndex == -1 ? "" : this.taskData.wfStepAuditModeList[this.auditIndex].id),
        taskId: this.taskData.wfTaskModel.id,
        sessionId: this.userInfo.sessionId
      })
      uni.hideLoading();
      uni.hideNavigationBarLoading();
      if (data.code === 0) {
        if (data.data !== "") {
          uni.showModal({
            title: '提示',
            content: data.data,
            showCancel: false,
          })
        } else {
          let taskId = this.taskData.wfTaskModel.id;
          let stepId = this.taskData.wfTaskModel.stepId;
          let stepNo = this.taskData.wfStepModel.stepNo;
          let flowId = this.taskData.wfModel.id;
          let auditId = (this.auditIndex == -1 ? "" : this.taskData.wfStepAuditModeList[this.auditIndex].id);
          routeTo({
            link: 'auditaction',
            params: {
              scan: this.scan,
              auditId: auditId,
              flowId: flowId,
              stepNo: stepNo,
              stepId: stepId,
              taskId: taskId,
              t: (this.auditIndex == -1 ? "" : this.taskData.wfStepAuditModeList[this.auditIndex].auditName)
            }
          })
        }
      } else {
        wx.showModal({
          title: '提示',
          content: '保存审核动作异常!',
          showCancel: false,
        })
      }
    },
    async sendAudit(e) {

      let formData = JSON.stringify(this.mobileEntityModeList[0].data[0])

      if (this.taskData.wfStepAuditModeList[e].isFormCheck === 0) {
        //校验数据
        let verifyData_status = this.verifyData(true);
        if (!verifyData_status) {
          return;
        }
      }


      this.auditIndex = e;
      if (formData === this.originData) {
        // routeTo('soterSetting')
        await this.saveSubTableData()
        await this.saveAudit()
      } else {
        let data = await this.saveData();
        await this.saveSubTableData()
        if (data.code === 0) {
          if (data.data !== "") {
            uni.showModal({
              title: '提示',
              content: data.data,
              showCancel: false,
            })
          } else {
            await this.saveAudit()
          }
        } else {
          uni.showModal({
            title: '提示',
            content: '保存审核动作异常!',
            showCancel: false,
          })
        }
      }
    },
    showMore() {
      let that = this;
      uni.showActionSheet({
        itemList: this.taskData.wfStepAuditModeList.map(e => e.auditName),
        success(res) {
          that.auditIndex = res.tapIndex;
          that.saveAudit()
        }
      })
    },
    async saveData() {
      uni.showLoading({
        title: '保存数据',
        mask: true,
      })
      uni.showNavigationBarLoading();
      let data = await this.api.saveFormData({
        sessionId: this.userInfo.sessionId,
        taskId: this.taskData.wfTaskModel.id,
        instanceId: this.mobileEntityModeList[0].data[0].INSTANCEID,
        formDate: this.mobileEntityModeList[0].data[0],
        entityTableName: this.mobileEntityModeList[0].entityname,
        formId: this.taskData.wfStepModel.formId,
        mainId: this.mobileEntityModeList[0].data[0].ID
      })
      uni.hideLoading();
      uni.hideNavigationBarLoading()
      return data;
    },
    async fetchData() {
      let that = this;
      uni.showLoading({
        title: '正在加载'
      })
      let data = await this.api.getOpenTask({
        sessionId: this.userInfo.sessionId,
        taskId: this.id,
        openStatus: this.openStatus
      })
      if (data.data.error == true) {
        uni.showToast({
          title: data.data.msg,
          duration: 2000,
          icon: "none"
        });
        setTimeout(function () {
          uni.navigateBack({
            delta: 1,
          })
          uni.$emit('update', {
            payload: '刷新待办'
          })
        }, 2000)
        return
      }
      this.taskData = data.data;
      // this.setTaskData(data.data)
      this.$store.dispatch('setTaskData', data.data)
      this.originData = JSON.stringify(this.mobileEntityModeList[0].data[0])
      uni.hideLoading();
      console.log(this.taskData, "获取到的数据")
      if (this.openStatus == 8 && ([ 0, 1, 2, 5 ].indexOf(this.taskData.wfTaskModel.status)) != -1) {

      } else {
        // #ifdef APP-PLUS
        let webView = this.$mp.page.$getAppWebview();
        webView.setTitleNViewButtonStyle(0, {
          text: ' ',
        });
        // #endif

        // #ifdef H5
        // #endif
      }
    },
    async circulateAfter() {
      uni.showLoading({
        title: '保存数据',
        mask: true,
      })
      uni.showNavigationBarLoading();
      let data = await this.api.circulateAfter({
        sessionId: this.userInfo.sessionId,
        taskId: this.taskData.wfTaskModel.id,
        stepId: this.taskData.wfStepModel.id,
        stepNo: this.taskData.wfStepModel.stepNo,
        flowId: this.taskData.wfModel.id
      })
      uni.hideLoading();
      uni.hideNavigationBarLoading()
      if (data.code == 0) {
        let data_ = JSON.parse(data.data);
        if (data_.code == 0) {
          uni.showToast({
            title: '任务办理成功!',
            duration: 2000,
          });
          setTimeout(function () {
            uni.navigateBack({
              delta: 1,
            })
            uni.$emit('update', {
              payload: '刷新待办'
            })
          }, 2000)
        } else {
          uni.showToast({
            title: data_.msg,
            duration: 2000,
            icon: "none"
          });
        }
      } else {
        uni.showToast({
          title: data.msg,
          duration: 2000,
          icon: "none"
        });
      }
    },
    async modifiedTask() {
      //校验数据
      let verifyData_status = this.verifyData(true);
      if (!verifyData_status) {
        return;
      }

      let data = await this.saveData();
      await this.saveSubTableData();
      if (data.code === 0) {
        if (data.data !== "") {
          uni.showModal({
            title: '提示',
            content: data.data,
            showCancel: false,
          })
        } else {
          uni.showLoading({
            title: '办理中',
            mask: true,
          })
          uni.showNavigationBarLoading();
          let data = await this.api.modifiedTask({
            sessionId: this.userInfo.sessionId,
            taskId: this.taskData.wfTaskModel.id,
            stepId: this.taskData.wfStepModel.id,
            stepNo: this.taskData.wfStepModel.stepNo,
            flowId: this.taskData.wfModel.id
          })
          uni.hideLoading();
          uni.hideNavigationBarLoading();
          if (data.code == 0) {

            if (data.data == "") {
              uni.showToast({
                title: '任务办理成功!',
                duration: 2000,
              });
              setTimeout(function () {
                uni.navigateBack({
                  delta: 1,
                })

                uni.$emit('update', {
                  payload: '刷新待办'
                })
              }, 2000)
            } else {
              uni.showToast({
                title: "任务办理失败!",
                duration: 2000,
                icon: "none"
              });
            }
          } else {
            uni.showToast({
              title: data.msg,
              duration: 2000,
              icon: "none"
            });
          }

        }
      }

    }
  },
  async onNavigationBarButtonTap(e) {
    if (e.index === 0) {
      if (this.openStatus == 8 && ([ 0, 1, 2, 5 ].indexOf(this.taskData.wfTaskModel.status)) != -1) {
        let verifyData_status = this.verifyData(false);
        if (!verifyData_status) {
          return;
        }
        await this.saveData();
        await this.saveSubTableData();
      }
    }
  },
  onUnload(){
	  if(this.taskData && this.openStatus == 8){
	  		console.log('返回前保存')
	  		this.saveData();
	  }
  },
  onLoad(option) {
    uni.setNavigationBarTitle({
      title: option.title
    })
    this.title = option.title
    this.id = option.id;
    this.openStatus = option.openStatus;
    this.fetchData();
  },
  async onShow(){
    if (this.showRef) {
      await this.fetchData()
      this.showRef = false
      this.$refs.formItem.forEach(e=>e.init())
    }
  }
}
</script>

<style lang="less">
.form-page {
  background: #FFF;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 0 0 40rpx;
  /* #ifdef H5 */
  min-height: calc(100vh - 88rpx);
  /* #endif */

  .form {
    padding: 0 0 calc(40rpx + env(safe-area-inset-bottom)) 0;

    .form-body {
      //padding: 0 20rpx;
    }
  }

  .float-button {
    position: fixed;
    width: 100%;
    background-color: #FFF;
    padding: 0 0 env(safe-area-inset-bottom) 0;
    bottom: 0;
    display: flex;
    z-index: 2;
    align-items: center;
    box-shadow: -1px 0 5px #ccc;

    .button-group {
      display: flex;
      justify-content: center;
      flex: 1;
      align-content: center;

      :nth-child(2) {
        margin: 0 0 0 20rpx;
      }

      u-button {
        flex: 1;
        display: block;
      }
    }

    .more-btton {
      display: flex;
      color: #333;
      flex-direction: column;
      margin-right: 20rpx;
      align-items: center;
      justify-content: center;

      .icon-gengduo {
        font-size: 36rpx;
        margin-bottom: 5rpx;
      }

      .text {
        font-size: 20rpx;
      }
    }

  }

  .sub-table {
    margin-top: 20rpx;

    .table-name {
      background: #5f8ab4;
      padding: 20rpx;
      color: #FFF;
    }

    .deleteDataBtn {
      color: #FFF;
      float: right;
    }
  }

  .add-sub-table {
    padding: 20rpx;
    border: none;
    border-radius: 0;
    color: #0086FE;
    display: block;
    margin-bottom: 20rpx;

    button {
      border-radius: 0;
      color: #FFF;
      background: #5f8ab4;
    }
  }
}
</style>
